-- GreatPeopleMRLCPopup_Button
-- Author: yiboy
-- DateCreated: 11/29/2024 11:39:46 PM
--------------------------------------------------------------
-- ===========================================================================
--	INCLUDE
-- ===========================================================================
include("MRLC_SupportFunctions")
-- ===========================================================================
--	VARIABLES
-- ===========================================================================
local m_LaunchButtonInstance_MRLC = {};
local m_LaunchButtonLocked = false;

-- ===========================================================================
--	CONSTANTS
-- ===========================================================================
local m_propertyKey_1		:string		= "MayaRework_LongCount";
local m_propertyKey_2		:string		= "MayaRework_LongCount_Points";
local m_propertyKey_3		:string		= "MayaRework_LongCount_PointsUsed";

local m_gamePropertyKey_1		:string		= "MayaRework_LongCount_GameYear";

local m_IsXP1Active:boolean 	=	Modding.IsModActive("1B28771A-C749-434B-9053-D1380C553DE9");
local m_IsXP2Active:boolean 	= 	Modding.IsModActive("4873eb62-8ccc-4574-b784-dda455e74e68");
local m_IsHDActive:boolean 		=	Modding.IsModActive("521b8777-0977-4859-a5ee-3e411a732e5c");

local default_year_0_turn		= 113 
local hd_year_0_turn			= 69

--修改这个值以控制一次给几点
local m_BonusPointPerBaktun		= 1
-- ========================================================================================================================
--	FUNCTIONS
-- ========================================================================================================================

function MayaReworkLongCount_TogglePopup()
	m_LaunchButtonInstance_MRLC.MayaReworkLongCount_ItemAlertIndicator:SetHide(true)
	print("Toggle 001")
	LuaEvents.MRLC_TogglePopup()
	print("Toggle 002")
end

function AttachLaunchButton()
    local buttonStack = ContextPtr:LookUpControl("/InGame/LaunchBar/ButtonStack");

	--print("buttonStack=\t", buttonStack)

    ContextPtr:BuildInstanceForControl("MayaReworkLongCount_Item", m_LaunchButtonInstance_MRLC, buttonStack);


	--print("m_LaunchButtonInstance_MRLC=\t", m_LaunchButtonInstance_MRLC)
	--for k, v in pairs(m_LaunchButtonInstance_MRLC) do
		--print("k=\t", k)
		--print("v=\t", v)
	--end

	--print("=================================")
	--print("m_LaunchButtonInstance_MRLC.MayaReworkLongCount_ItemButton", m_LaunchButtonInstance_MRLC.MayaReworkLongCount_ItemButton)

	--m_LaunchButtonInstance_MRLC.MayaReworkLongCount_ItemIcon:SetTexture('LaunchBar_Hook_MRLC_Recruit');
	--m_LaunchButtonInstance_MRLC.MayaReworkLongCount_ItemIcon:SetColorByName('White');
    m_LaunchButtonInstance_MRLC.MayaReworkLongCount_ItemButton:RegisterCallback(Mouse.eLClick, MayaReworkLongCount_TogglePopup);
    ContextPtr:BuildInstanceForControl("MRLC_RecruitPinInstance", {}, buttonStack);

    -- Resize.
    buttonStack:CalculateSize();

    local backing = ContextPtr:LookUpControl("/InGame/LaunchBar/LaunchBacking");
    backing:SetSizeX(buttonStack:GetSizeX() + 116);

    local backingTile = ContextPtr:LookUpControl("/InGame/LaunchBar/LaunchBackingTile");
    backingTile:SetSizeX(buttonStack:GetSizeX() - 20);

    LuaEvents.LaunchBar_Resize(buttonStack:GetSizeX());
end

function OnMRLC_Recruit_ButtonSetup()
	if not playerHasPositiveNumberProperty(Game.GetLocalPlayer(), m_propertyKey_1) then
		return; 
	end
	
	if Players[Game.GetLocalPlayer()]:IsHuman() then
		if not m_LaunchButtonLocked  then
			AttachLaunchButton();
			m_LaunchButtonLocked = true
			Events.LocalPlayerTurnBegin.Remove( OnMRLC_Recruit_ButtonSetup );
		end
	end
end

function OnMRLC_CallLaunchButtonAlert()
	if m_LaunchButtonLocked then
		local pPlayer = Players[Game.GetLocalPlayer()]

		local points = pPlayer:GetProperty(m_propertyKey_2) or 0;
		local points_used = pPlayer:GetProperty(m_propertyKey_3) or 0;

		if points > points_used then
			m_LaunchButtonInstance_MRLC.MayaReworkLongCount_ItemAlertIndicator:SetHide(false)
		else
			m_LaunchButtonInstance_MRLC.MayaReworkLongCount_ItemAlertIndicator:SetHide(true)
		end
	end
end

function On_PlayerTurnActivated_MRLC(playerID, bIsFirstTime)
	if not bIsFirstTime then
		return
	end

	if not playerHasPositiveNumberProperty(playerID, m_propertyKey_1) then
		return; 
	end

	local pPlayer = Players[playerID]
	if not pPlayer:IsHuman() then
		return
	end

	--必须向引擎询问当前日期，给它回合数作为参数
	local turn = Game.GetCurrentGameTurn();
	local strDate = Calendar.MakeYearStr(turn);

	--它的回答会有几种可能
	--<Row Tag="LOC_TIME_AD">
			--<Text>{1_Date: number #} AD</Text>
		--</Row>
		--<Row Tag="LOC_TIME_BC">
			--<Text>{1_Date: number #} BC</Text>
		--</Row>
		--<Row Tag="LOC_TIME_MONTH">
			--<Text>{1_Date},{2_Month}</Text>
		--</Row>

	--<Replace Tag="LOC_TIME_AD" Language="zh_Hans_CN">
      --<Text>公元{1_Date: number #}年</Text>
    --</Replace>
    --<Replace Tag="LOC_TIME_BC" Language="zh_Hans_CN">
      --<Text>公元前{1_Date: number #}年 </Text>
    --</Replace>
    --<Replace Tag="LOC_TIME_MONTH" Language="zh_Hans_CN">
      --<Text>{1_Date},{2_Month}</Text>
    --</Replace>

	--<Replace Tag="LOC_TIME_AD" Language="zh_Hant_HK">
      --<Text>西元{1_Date: number #}年</Text>
    --</Replace>
    --<Replace Tag="LOC_TIME_BC" Language="zh_Hant_HK">
      --<Text>西元前{1_Date: number #}年</Text>
    --</Replace>
    --<Replace Tag="LOC_TIME_MONTH" Language="zh_Hant_HK">
      --<Text>{1_Date},{2_Month}</Text>
    --</Replace>

	 --<Replace Tag="LOC_TIME_AD" Language="ja_JP">
      --<Text>西暦{1_Date: number #}年</Text>
    --</Replace>
    --<Replace Tag="LOC_TIME_BC" Language="ja_JP">
      --<Text>紀元前{1_Date: number #}年</Text>
    --</Replace>
    --<Replace Tag="LOC_TIME_MONTH" Language="ja_JP">
      --<Text>{2_Month}月{1_Date}日</Text>
    --</Replace>

	--要么是公元前，要么是公元后，要么是月份，日期
	--最后一种情况只用于黑死病的CALENDAR_MONTHS（猜测）		
	
	--对于不同语言还不一样，离大谱啊

	--韩语日语法语是倒装的，有的中间还有空格

	--本地化语言
	local m_currentLanguage	= Locale.GetCurrentLanguage().Type;
	local m_year = -9999
	local has_error = false

	--先去除空格
	strDate = string.gsub(strDate, " ", "")
	--print("strDate=\t", strDate)

	if m_currentLanguage == "zh_Hans_CN" then
		if string.find(strDate, ",") then
			has_error = true
		else
			if string.find(strDate, "公元前") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="zh_Hant_HK" then
		if string.find(strDate, ",") then
			has_error = true
		else
			if string.find(strDate, "西元前") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="en_US" then
		if string.find(strDate, ",") then
			has_error = true
		else
			if string.find(strDate, "BC") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="ja_JP" then
		if string.find(strDate, "日") then
			has_error = true
		else
			if string.find(strDate, "元前") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="de_DE" then
		if string.find(strDate, ",") then
			has_error = true
		else
			if string.find(strDate, "v. Chr.") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="es_ES" then
		if string.find(strDate, ",") then
			has_error = true
		else
			if string.find(strDate, "a. C.") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="fr_FR" then
		if string.find(strDate, "J.-C.") == nil then
			has_error = true
		else
			if string.find(strDate, "av. J.-C.") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="it_IT" then
		if string.find(strDate, ",") then
			has_error = true
		else
			if string.find(strDate, "a.C.") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="ko_KR" then
		if string.find(strDate, "?") then
			has_error = true
		else
			if string.find(strDate, "???") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="pl_PL" then
		if string.find(strDate, ",") then
			has_error = true
		else
			if string.find(strDate, "p.n.e.") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="pt_BR" then
		if string.find(strDate, ",") then
			has_error = true
		else
			if string.find(strDate, "a.C.") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	elseif m_currentLanguage =="ru_RU" then
		if string.find(strDate, ",") then
			has_error = true
		else
			if string.find(strDate, "до н. э.") then
				local number_list = MyGetNumbersInString(strDate)
				m_year = -number_list[1]
			else
				local number_list = MyGetNumbersInString(strDate)
				m_year = number_list[1]
			end
		end

	end

	if has_error then
		print("calendar error!")
		return
	end

	--print("m_year=\t", m_year)

	--对m_year做一个正负判断

	if m_IsHDActive then
		if turn < hd_year_0_turn	then
			m_year = - math.abs(m_year)
		end
	else
		if turn < default_year_0_turn	then
			m_year = - math.abs(m_year)
		end
	end

	--print("m_year_after=\t", m_year)

	local game_year_label = Game:GetProperty(m_gamePropertyKey_1) or -99999
	local points = pPlayer:GetProperty(m_propertyKey_2) or 0;

	local baktunOrder = -3

	for row in GameInfo.MayaUA_baktun_Years() do
		if game_year_label < row.BaktunYear and m_year >= row.BaktunYear then
			--增加m_BonusPointPerBaktun个点数

			baktunOrder = row.BaktunOrder

			local tParameters:table = {}
			tParameters['OnStart'] 		= 'MayaReworkLongCount_SetProperty';
			tParameters['Key'] 			= m_propertyKey_2;
			tParameters['Value'] 		= points + m_BonusPointPerBaktun
			UI.RequestPlayerOperation(playerID, PlayerOperations.EXECUTE_SCRIPT, tParameters)

			local kParameters:table = {}
			kParameters['OnStart'] 		= 'MayaReworkLongCount_SetGameProperty';
			kParameters['Key'] 			= m_gamePropertyKey_1;
			kParameters['Value'] 		= row.BaktunYear
			UI.RequestPlayerOperation(playerID, PlayerOperations.EXECUTE_SCRIPT, kParameters)

			print("point added success!")

			m_LaunchButtonInstance_MRLC.MayaReworkLongCount_ItemAlertIndicator:SetHide(false)

			SendNotification_MRLC(playerID, baktunOrder, m_BonusPointPerBaktun)

			--这个break有点脱裤子放屁，但是就这样吧
			break
		end

	end

end

function SendNotification_MRLC(playerID, baktunOrder, bonus_point)
	local tNotificationData = {}
	tNotificationData[ParameterTypes.MESSAGE] = Locale.Lookup('LOC_NOTIFICATION_MRLC_NEW_POINTS_MESSAGE')
	tNotificationData[ParameterTypes.SUMMARY] = Locale.Lookup('LOC_NOTIFICATION_MRLC_NEW_POINTS_SUMMARY', baktunOrder, bonus_point)

	local mHash	= DB.MakeHash('NOTIFICATION_MRLC_NEW_POINTS');

	NotificationManager.SendNotification(playerID, mHash, tNotificationData)
end

function Initialize()
	
    OnMRLC_Recruit_ButtonSetup()
	Events.LocalPlayerTurnBegin.Add( OnMRLC_Recruit_ButtonSetup );

	--LuaEvents.MRLC_CallLaunchButtonAlert.Add( OnMRLC_CallLaunchButtonAlert)

	Events.UnitGreatPersonCreated.Add( OnMRLC_CallLaunchButtonAlert)

	Events.PlayerTurnActivated.Add(On_PlayerTurnActivated_MRLC)

end

Events.LoadGameViewStateDone.Add( Initialize );
print("Maya Rework Long Count Button Initialized!")